<?php
	session_start();//用于登录之后的验证
	$sessionId = isset($_SESSION['sessionId'])?$_SESSION['sessionId']:null;
	//目前进行session验证,并把数据显示出来
	
	include_once("./public/common.php");
	include_once("./public/verify.php");
	include_once("./public/opDB.php");
	
	
	//TODO:目前是不完全的验证，did直接传，虽然由session可以保证用户合法...（但在一些云平台上不能使用SESSSION）
	$did = getPostPara("did");
	$spesa = getPostPara('spesa');
	$speu = getPostPara('speu');
	$addDevice = getPostPara('addDevice');
	$deleteDevice = getPostPara('deleteDevice');
	
	$salt = specialDecode($spesa,$constSalt);
	$uid = specialDecode($speu,$constSalt);
	
	
	
	if($spesa == null || $speu == null || $sessionId == null){
		echo "404";
		return false;
	}
	if($addDevice == null && $deleteDevice == null){
		echo "404";
		return false;
	}
	
	//分两类：add传感器，则序号为当前最大序号+1，delete传感器先要确定该传感器是否存在
	if($addDevice != null && strcmp($addDevice,'add')==0){
		include_once("public/opDB.php");	
		$row = mysql_query('select max(did) mx from device');
		$res = mysql_fetch_array($row);
		$did = intval($res['mx'])+1;
		$hadevice = substr(specialEncode($did,$constSalt),0,32);
		mysql_query('insert into device(did,uid,hadevice,delflag) values('.$did.','.$uid.',"'.$hadevice.'",0)') or die('fail to insert');
		echo "ok to add";
		mysql_close($con);	
	}else if($deleteDevice != null && strcmp($deleteDevice,'delete')==0 || $did == null){
		$did = intval($did);
		include_once("public/opDB.php");
		$res = mysql_query('select did from device where did='.$did.' limit 0,1') or die('fail to find');
		$row = mysql_fetch_array($res);
		if(empty($row)){
			mysql_close($con);
			echo 'fail to find';
			return false;
		}
		mysql_query('delete from device where did='.$did.' limit 1	') or die('fail to delete');
		echo "ok to delete!";
		mysql_close($con);	
	}else{
		echo "404";
		return false;		
	}
	
	
	echo "<h1>(～￣▽￣)～ operation success</h1><br/>";
	echo 'you will be back in 1 seconds......<br />';
	echo '<meta http-equiv="Refresh" content="1;url=http://127.0.0.1:8080/phctrl/chart/deviceManage.php?spesa='.$spesa.'&speu='.$speu.'">';
	echo 'if not return , click here<p></p>';
	echo '<a href="http://127.0.0.1:8080/phctrl/chart/deviceManage.php?spesa='.$spesa.'&speu='.$speu.'">return</a>';

	
	
?>